package com.saikei.demoapp.db

import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import androidx.room.Relation


@Entity("user")
class User(
    @PrimaryKey(autoGenerate = true)
    var userId: Int? = null,
    val name: String? = null,
    val password: String? = null,
) {
    override fun toString(): String {
        return "User(id=$userId, name=$name, password=$password)"
    }
}

@Entity(
    "book", foreignKeys = [
        ForeignKey(
            entity = User::class,
            parentColumns = ["userId"],
            childColumns = ["ownerUserId"],
            onDelete = ForeignKey.CASCADE // 🔥 关键：启用级联删除
        )
    ],
    indices = [Index("ownerUserId")] // 推荐加索引提高查询效率
)
class Book(
    @PrimaryKey(autoGenerate = true)
    val bookId: Int? = null,
    val name: String? = null,
    val password: String? = null,
    val ownerUserId: Int? = null
) {
    override fun toString(): String {
        return "Book(bookId=$bookId, name=$name, password=$password, 关联用户=$ownerUserId)"
    }
}

data class UserWithBooks(
    @Embedded
    val user: User? = null,
    @Relation(parentColumn = "userId", entityColumn = "ownerUserId")
    val books: List<Book>? = null
) {
    override fun toString(): String {
        return "UserWithBooks(用户=$user, 用户书籍=$books)"
    }
}